﻿using System;
using System.Diagnostics.Contracts;
using System.IO;
using O1.Data;

namespace O1.IO
{
    [ContractVerification(true)]
    internal static class PersistenceExtensions
    {
        public static void WriteCell(this byte[] cell, Stream output)
        {
            Contract.Requires(output != null);
            Contract.Requires(output.CanWrite);

            cell.WriteCell(output, new byte[4]);
        }

        public static void WriteCell(this byte[] cell, Stream output, byte[] buffer)
        {
            Contract.Requires(output != null);
            Contract.Requires(output.CanWrite);
            Contract.Requires(buffer != null);
            Contract.Requires(buffer.Length >= 4);

            if (cell == null)
            {
                (Sz.CLR.Int32 + 1).CopyBytes(buffer, 0);
                output.Write(buffer, 0, Sz.CLR.Int32);
                0.CopyBytes(buffer, 0);
                output.Write(buffer, 0, Sz.CLR.Int32);
                output.WriteByte(0);
                return;
            }

            var size = cell.Length;
            cell.Length.CopyBytes(buffer, 0);
            output.Write(buffer, 0, Sz.CLR.Int32);
            output.Write(cell, 0, size);
        }
    }
}
